/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.convert.vienna;

import at.schauer.gregor.vienna.convert.factory.ConverterFactory;
import at.schauer.gregor.vienna.convert.factory.ConverterFactoryAware;
import at.schauer.gregor.vienna.convert.provider.AbstractConverterProvider;
import at.schauer.gregor.vienna.exception.ViennaException;
import at.schauer.gregor.vienna.util.JavassistMetadataAdapter;
import at.schauer.gregor.vienna.util.ViennaUtils;
import com.google.common.base.Predicates;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Iterables;
import com.google.common.collect.Table;
import org.apache.commons.lang3.reflect.ConstructorUtils;
import org.reflections.ReflectionUtils;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;

import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Set;

/**
 * @author Gregor Schauer
 */
public class ViennaConverterProvider<C extends SimpleConverter> extends AbstractConverterProvider<C> implements ConverterFactory<C> {
	Table<Class<?>, Class<?>, C> converterTable = HashBasedTable.create();

	public ViennaConverterProvider() {
		registerAll(ViennaConverterProvider.class.getPackage().getName());
	}

	@SuppressWarnings("unchecked")
	public void registerAll(String packageName) {
		Reflections reflections = //new Reflections(packageName, new SubTypesScanner(true));

				new Reflections(new ConfigurationBuilder()
						.setMetadataAdapter(new JavassistMetadataAdapter())
						.setScanners(new SubTypesScanner(false))
						.setUrls(ClasspathHelper.forPackage(packageName))
						//.filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName)))
				);

		try {
			Set<Class<? extends SimpleConverter>> classes = reflections.getSubTypesOf(SimpleConverter.class);
			for (Class<? extends SimpleConverter> clazz : classes) {
				if (!Modifier.isAbstract(clazz.getModifiers()) && !clazz.isInterface()) {
					register((C) ConstructorUtils.invokeExactConstructor(clazz));
				}
			}
		} catch (Exception e) {
			throw new ViennaException(e);
		}
	}

	public void register(C converter) {
		Map<Type, Class> genericTypes = ViennaUtils.TypeUtils.getGenericTypes(converter.getClass());
		Class type = Iterables.getFirst(genericTypes.values(), null);
		if (type != null) {
			register(type, converter);
		}
		if (converter instanceof ConverterFactoryAware) {
			((ConverterFactoryAware) converter).setConverterFactory(this);
		}
	}

	@Override
	public C register(Class<?> type, C converter) {
		type = getType(type);
		converterTable.put(type, String.class, converter);
		converterTable.put(String.class, type, converter);
		return converter;
	}

	@Override
	public <S, T> C getConverter(Class<S> sourceClass, Class<T> targetClass) {
		Class<?> sourceType = getType(sourceClass);
		Class<?> targetType = getType(targetClass);
		return converterTable.get(sourceType, targetType);
	}

	@Override
	@SuppressWarnings("unchecked")
	public <X, Y> Y convert(X source, Class<Y> targetClass) {
		Class<?> sourceClass = getType(source.getClass());
		C converter = getConverter(sourceClass, getType(targetClass));
		while (converter == null) {
			if (source instanceof String) {
				for (Class<?> superType : ReflectionUtils.getAllSuperTypes(targetClass, Predicates.alwaysTrue())) {
					converter = getConverter(sourceClass, superType);
					if (converter != null) {
						break;
					}
				}
			} else {
				for (Class<?> superType : ReflectionUtils.getAllSuperTypes(sourceClass, Predicates.alwaysTrue())) {
					converter = getConverter(superType, targetClass);
					if (converter != null) {
						break;
					}
				}
			}
		}

		if (source instanceof String) {
			return (Y) converter.sourceToTarget((String) source, targetClass);
		} else {
			return (Y) converter.targetToSource(source);
		}
	}

	protected Class<?> getType(Class<?> clazz) {
		return clazz.isArray() ? Object[].class : clazz;
	}
}
